package com.zjsd.sqeybusiness.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.zjsd.sqeybusiness.domain.Wechatconfig;
import com.zjsd.sqeybusiness.dto.ShareparamDTO;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WxSignatureUtil {
    private static final String APP_ID = "wxd81a6bd295facda3";
    private static final String APP_SECRET = "97bceab2781722d49b12406bdb24ffd2";

    public static ShareparamDTO getSignature(String ticket , ShareparamDTO shareparamDTO) throws IOException {
        String nonceStr = generateRandomString();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String orderedStr = String.format(
                "jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",
                ticket, nonceStr, timestamp, formatUrl(shareparamDTO.getUrl())
        );
        System.out.println("orderedStr: " + orderedStr);
        String signature = sha1(orderedStr);
        System.out.println("url: " + shareparamDTO.getUrl());
        System.out.println("signature: " + signature);
        System.out.println("nonceStr: " + nonceStr);
        System.out.println("timestamp: " + timestamp);
        System.out.println("APP_ID: " + APP_ID);
        shareparamDTO.setSignature(signature);
        shareparamDTO.setAppId(APP_ID);
        shareparamDTO.setNonceStr(nonceStr);
        shareparamDTO.setTimestamp(timestamp);
        return shareparamDTO ;
    }

    public static String getJsapiTicket(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("ticket");
    }

    private static String generateRandomString() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(16);
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (int i = 0; i < 16; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }


    public static String sha1(String input) {
        try {
            System.out.println("SHA-1加密前：" + input);
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexStr = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexStr.append('0');
                hexStr.append(hex);
            }
            return hexStr.toString();
        } catch (Exception e) {
            throw new RuntimeException("SHA-1加密失败", e);
        }
    }


    public static void main(String[] args) {
        String jsapiTicket = "sM4AOVdWfPE4DxkXGEs8VM...";
        String nonceStr = "Wm3WZYTPz0wzccnW";
        long timestamp = 1414587457L;
        String url = "http://example.com/page?param=test";

        // 处理URL
        String formattedUrl = formatUrl(url);

        // 拼接参数
        String signStr = String.format(
                "jsapi_ticket=%s&noncestr=%s×tamp=%d&url=%s",
                jsapiTicket, nonceStr, timestamp, formattedUrl
        );

        // 生成签名
        String signature = sha1(signStr);
        System.out.println("Signature: " + signature);
    }

    public static String formatUrl(String url) {
        if (url.contains("#")) {
            url = url.split("#")[0];
        }
        return url;
    }

}